//
//  HMSportTracking.m
//  黑马行
//
//  Created by 宇宙执政 on 16/9/19.
//  Copyright © 2016年 yujianbinMAC. All rights reserved.
//

#import "HMSportTracking.h"
#import <MAMapKit/MAMapKit.h>

@implementation HMSportTracking{
    
    //起始点位置
    CLLocation *_startLocation;
    
    ///所有运动线条模型的数组
    NSMutableArray <HMSportTrackingLine *>*_trackingLines;
    
}

-(instancetype)initWithType:(HMSportType)type state:(HMSportState)state{
    
    if (self = [super init]) {
        _sportType = type;
        _sportState = state;
        
        _trackingLines = [NSMutableArray array];
    }
    return self;
}

-(UIImage *)sportImage{
    
    UIImage *image;
    switch (_sportType) {
        case HMSportTypeRun:
            image = [UIImage imageNamed:@"map_annotation_run"];
            break;
        case HMSportTypeWalk:
            image = [UIImage imageNamed:@"map_annotation_walk"];
            break;
        case HMSportTypeBike:
            image = [UIImage imageNamed:@"map_annotation_bike"];
            break;
        default:
            break;
    }
    
    return image;
}

-(CLLocation *)startLocation{
    
    return _trackingLines.firstObject.startLocation;
}

-(void)setSportState:(HMSportState)sportState{
    
    _sportState = sportState;
    if (_sportState != HMSportStateContinue) {
        _startLocation = nil;
    }
    
}

-(MAPolyline *)appendLocation:(CLLocation *)location{
    
    
    // 将定位时间和当前时间做比较，如果差值过大，说明 GPS 信号不好（室内／初始定位)
    // 目的：性能优化，减少不必要的数据点，减少杂线！
    if ([[NSDate date] timeIntervalSinceDate:location.timestamp] > 2) {
        return nil;
    }
    
    //1,判断起始点是否存在
    if (_startLocation == nil) {
        _startLocation = location;
        
        return nil;
    }
    
    //2,判断运动速度
    if (location.speed <= 0) {
        return nil;
    }
    
    //3，创建轨迹追踪线条模型
    HMSportTrackingLine *trackingLine = [[HMSportTrackingLine alloc] initWithStartLocation:_startLocation endLocation:location];
    
    [_trackingLines addObject:trackingLine];
    
    NSLog(@"%f - %f - %f - %f", self.avgSpeed, self.maxSpeed, self.totalTime, self.totalDistance);
    
    //4,将当前位置作为下一次起始位置
    _startLocation = location;
    
    //5,返回折线模型
    return trackingLine.polyline;
}

-(double)avgSpeed{
    
    return [[_trackingLines valueForKeyPath:@"@avg.speed"] doubleValue];
}

-(double)maxSpeed{
    
    return [[_trackingLines valueForKeyPath:@"@max.speed"] doubleValue];
    
}

-(double)totalTime{
    
    return [[_trackingLines valueForKeyPath:@"@sum.time"] doubleValue];
}

-(double)totalDistance{
    
    return [[_trackingLines valueForKeyPath:@"@sum.distance"] doubleValue];
    
}

@end
